package com.bungarus.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import io.netty.util.AsciiString;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by tang on 2019/1/7.
 */
public class ProtobufWrappedWithHttpServerEncoder extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof ByteBuf) {
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK);

            final Date today = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime();
            final SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM, yyyy HH:mm:ss z");

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.BYTES);
            response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
            response.headers().set(HttpHeaderNames.SERVER, AsciiString.cached("BUNGARUS/1.0.0"));
            response.headers().set(HttpHeaderNames.DATE, AsciiString.cached(sdf.format(today)));
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, ((ByteBuf) msg).readableBytes());
            response.content().writeBytes((ByteBuf)msg);

            ctx.writeAndFlush(response, promise);
        }
        else {
            super.write(ctx, msg, promise);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
